package polyu.comp;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import android.os.*;
import android.util.Log;

public class PushThread extends Thread {
	
	
	private Socket mSock;
	Handler hMain;
	

	
	public PushThread(Socket s, Handler h) {
		this.mSock = s;
		this.hMain = h;
	}
	
	

	@Override
	public void run() {
		try {
			PrintWriter out = new PrintWriter(mSock.getOutputStream(), true);
			BufferedReader in = new BufferedReader(new InputStreamReader(mSock.getInputStream()));
			
			// send request
			String cmd = String.format("push %s", Util.uid);
			out.println(cmd);
			// check return
			String ret = in.readLine();
			if (ret.equals("ok"))
				Log.v("aa", "Begin to wait for push");
			
			while (mSock.isConnected()) {
				ret = in.readLine();
				if (ret == null || ret.isEmpty()) {
					mSock.close();
					break;
				}
				// Send Message to main thread
				Message msg = new Message();
                msg.obj = ret.trim();
                msg.what = 4009;
                hMain.sendMessage(msg);
			}
			
			// clean ups
			out.close();
			in.close();
			mSock.close();
		} catch (Exception e) {
			Log.e("aa", "Terminated by User, no error");
		}


	}

}
